package com.ruike.alisurface.ui.mainPage;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.SystemClock;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ruike.alisurface.BuildConfig;
import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.http.MchApiHttp;
import com.ruike.alisurface.ui.setting.SettingActivity;
import com.ruike.alisurface.utils.DeviceUtils;
import com.ruike.alisurface.utils.ShareKey;
import com.ruike.alisurface.utils.ZXingUtils;
import com.tencent.rtmp.TXVodPlayer;
import com.tencent.rtmp.ui.TXCloudVideoView;
import com.voodoo.lib_utils.AssetsUtils;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.ShareUtils;
import com.voodoo.lib_utils.imageLoader.ImageLoader;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;

import static com.ruike.alisurface.utils.ShareKey.BASEUSERID;

/**
 * Author: voodoo
 * CreateDate: 2020-03-29 029 下午 09:49
 * Description: 登录界面
 */
public class LoginActivity extends BaseAty {

    @BindView(R.id.login_video_txcvv)
    TXCloudVideoView loginVideoTxcvv;
    @BindView(R.id.login_versionName_tv)
    TextView loginVersionNameTv;
    @BindView(R.id.login_account_ll)
    LinearLayout pwdLoginLlayout;
    @BindView(R.id.login_qrcode_ll)
    LinearLayout qrcodeLoginLlayout;
    @BindView(R.id.login_imgcode)
    ImageView mCodeImg;
    @BindView(R.id.login_userName_et)
    EditText loginUserNameEt;
    @BindView(R.id.login_userPwd_et)
    EditText loginUserPwdEt;
    @BindView(R.id.login_sn_tv)
    TextView loginSnTv;
    private TXVodPlayer mVodPlayer;

    @Override
    protected boolean getCanToOtherApp() {
        return true;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initViews() {
        L.i("登录页==" + this.getClass().getName());
        startCountdownTimer(60, null, null);
    }

    @Override
    protected void initData() {
        loginVersionNameTv.setText(new StringBuffer(getResources().getString(R.string.versionNameStr)).append(BuildConfig.VERSION_NAME));
        loginSnTv.setText(new StringBuffer(getResources().getString(R.string.deviceSnStr)).append(DeviceUtils.getDeviceSn()));
        playVideo();
        setLoginType();
    }

    private void setLoginType() {
        boolean isPwdLogin = ShareUtils.getInstance().getBoolean(ShareKey.IS_PWD_LOGIN);
        pwdLoginLlayout.setVisibility(isPwdLogin ? View.VISIBLE : View.GONE);
        qrcodeLoginLlayout.setVisibility(isPwdLogin ? View.GONE : View.VISIBLE);
        if (!isPwdLogin) {
            String jsonSN = "http://m.shouhuojiyun.com/android_login/index.html?sn=" + DeviceUtils.getDeviceSn();
            Bitmap SnBitmap = ZXingUtils.getInstance().createQRImage((jsonSN), 300, 300, BitmapFactory.decodeResource(getResources(), 0));
            if (SnBitmap == null) {
                showErrorTip("生成的二维码异常");
                startCountdownTimer(3, null, null);
                return;
            }
            ImageLoader.loadImage(this, SnBitmap, mCodeImg);
        }
    }

    /**
     * player对象创建
     */
    private void playVideo() {
        // 创建  对象
        mVodPlayer = new TXVodPlayer(this);
        //关键 player 对象与界面 view
        mVodPlayer.setPlayerView(loginVideoTxcvv);
        File file = AssetsUtils.getFile(this, "video_sunny.mp4");
        if (file != null && file.exists()) {
            mVodPlayer.startPlay(file.getAbsolutePath());
            mVodPlayer.setLoop(true);
        }
    }

    @OnClick({R.id.login_goback_imgv, R.id.login_login_btn, R.id.login_versionName_tv})
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.login_goback_imgv:
                startCountdownTimer(0, null, null);
                break;
            case R.id.login_versionName_tv:
                continuousClick();
                break;
            case R.id.login_login_btn:
                String userNameStr = loginUserNameEt.getText().toString().trim();
                String userPwdStr = loginUserPwdEt.getText().toString().trim();
                if (userNameStr.isEmpty()) {
                    showErrorTip("请输入账号");
                    return;
                }
                if (userPwdStr.isEmpty()) {
                    showErrorTip("请输入密码");
                    return;
                }
                showProgressDialog("登录中，请等待。。。");
                MchApiHttp.getLogin(this, userNameStr, userPwdStr);
                break;
        }
    }

    @Override
    public void onSuccess(String requestUrl, String requestJsonStr) {
        super.onSuccess(requestUrl, requestJsonStr);
        if (requestUrl.endsWith("LoginByMch")) {
            L.i(" lgoin==  onSuccess ", requestJsonStr);
            try {
                JSONObject object = new JSONObject(requestJsonStr);
                String msg = object.getString("msg");
                int code = object.getInt("code");
                L.i("===msg==" + msg + "===code===" + code);
                JSONObject data = object.optJSONObject("data");
                if (data != null) {
                    String uid = data.getString("uid");
                    ShareUtils.getInstance().putString(ShareKey.UID, uid);
                    jumpToSetting();
                } else {
                    showErrorTip("返回的uid异常");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onError(String requestUrl, String errorMsg) {
        super.onError(requestUrl, errorMsg);
        if (requestUrl.endsWith("LoginByMch")) {
            L.i(" lgoin==  onError ", errorMsg);
            showErrorTip(errorMsg);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 暂停播放
        if (mVodPlayer != null) {
            mVodPlayer.pause();
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        // 恢复播放
        if (mVodPlayer != null) {
            mVodPlayer.resume();
        }
    }

    @Override
    public void doEventBusResult(MsgEventBus event) {
        if (event.getType().equals("login") && event.getMessage().equals("跳转后台")) {
            jumpToSetting();
        }
    }

    private void jumpToSetting() {
        startActivity(SettingActivity.class, null);
        finish();
    }

    final static int COUNTS = 5;// 点击次数
    final static long DURATION = 2000;// 规定有效时间
    long[] mHits = new long[COUNTS];

    // 多次连续点击
    protected void continuousClick() {
        // 每次点击时，数组向前移动一位
        System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
        // 为数组最后一位赋值
        mHits[mHits.length - 1] = SystemClock.uptimeMillis();
        if (mHits[0] >= (SystemClock.uptimeMillis() - DURATION)) {
            mHits = new long[COUNTS]; // 重新初始化数组
            ShareUtils.getInstance().putBoolean(ShareKey.IS_PWD_LOGIN, !ShareUtils.getInstance().getBoolean(ShareKey.IS_PWD_LOGIN));
            setLoginType();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mVodPlayer.stopPlay(true); // true 代表清除最后一帧画面
        loginVideoTxcvv.onDestroy();
        loginVideoTxcvv = null;
    }
}
